<template>
    <section class="CartView">
        <div class="header">
            <!-- 头部导航栏 -->
            <van-nav-bar title="嗨购商城" left-text="返回" left-arrow>
                <!-- 右侧气泡弹出层 -->
                <template #right>
                    <van-popover v-model="showPopover" trigger="click" :actions="actions" placement="bottom-end" theme="dark" @select="onSelect">
                        <template #reference>
                            <van-icon name="ellipsis" size="24" color="black" />
                        </template>
                    </van-popover>
                </template>
                <!-- 左侧返回按钮 -->
                <template #left>
                    <van-icon name="arrow-left"  @click="$router.back()" size="24" color="black" ></van-icon>
                </template>
            </van-nav-bar>
                <!-- 分享模块--气泡弹出层 -->
            <van-share-sheet v-model="showShare" title="立即分享给好友" :options="options" />
        </div>
        <div class="cartMain">
            <!-- 购物车数据模块列表 -->
            <div class="cartlist">
              <!-- 购物车无数据状态展示 -->
              <van-empty
                class="custom-image"
                image="https://img11.360buyimg.com/jdphoto/s180x180_jfs/t18163/292/540553659/74408/adeb7463/5a93c51cN3bb5e37b.png"
                description="购物车空空如也，去逛逛吧~"
                v-if="!cartList"
                />
                <!-- 购物车数据 -->
                <div v-else>
                  <div class="list_box" v-for="item in cartList" :key="item.proid">
                    <div class="head">
                      <p><van-icon name="shop-o" color="#666" size="14" />嗨购商城官方旗舰店<van-icon name="arrow" size="14" color="#666" /></p>
                      <p class="but" v-if="!item.isflag">等待付款</p>
                    </div>
                  <div class="list_item">
                      <!-- 产品多选框 -->
                      <div><van-checkbox v-model="item.flag" @click="checkbox(item)" name="check"></van-checkbox></div>
                      <!-- 产品图片 -->
                      <img :src="item.img1" alt="">
                      <!-- 产品信息----价格、标题、数量 -->
                      <div class="listInfo">
                        <!-- 产品标题 -->
                        <div class="title van-multi-ellipsis--l2">{{ item.proname }}</div>
                        <div class="info">
                          <!-- 产品单价 -->
                          <span class="price"><i>￥</i>{{ item.originprice | setPriceInt }}<i>.{{ item.originprice | setPriceFloat }}</i></span>
                          <!-- 产品数量 -->
                          <div class="num">
                            <button @click="subtract(item.cartid, item.num)">-</button>
                            <input type="number" v-model="item.num" name="" id="">
                            <button @click="addition(item.cartid, item.num)">+</button>
                          </div>
                        </div>
                        <!-- 购物车商品操作 -->
                        <p class="remove"><span @click="removeId(item.cartid)">删除</span>|<span @click="move(item.cartid)">移入关注</span></p>
                      </div>
                  </div>
                  </div>
                </div>
                <!-- 提交订单 + 全选状态 -->
                <van-submit-bar :price="totalPrice" button-text="提交订单" @submit="onSubmit" v-show="cartList.length">
                  <van-checkbox v-model="checked" @click="checkAll" name="allcheck">全选</van-checkbox>
                </van-submit-bar>
            </div>
            <!-- 分割线 -->
            <van-divider>可能你还想要</van-divider>
            <!-- 上拉加载和推荐列表模块 -->
            <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad" :immediate-check="false" >
                <pro-list :proList="prolist"></pro-list>
            </van-list>
        </div>
    </section>
</template>
<style lang="stylus" scoped >
.list_box
  padding .625rem
  margin-top 1.25rem
  display flex
  background-color white
  border-radius .625rem
  flex-direction column
  .head
    display flex
    font-size .875rem
    justify-content space-between
    p
      display flex
      align-items center
  .but
      color red
  .evenbut
      color #000
.list_item
    display flex
    height 7.375rem
    align-items center
    img
      width 6rem
      height 6rem
      margin 0 .625rem
      border-radius .625rem
    .listInfo
      display flex
      flex-direction column
      justify-content space-evenly
      height 100%
      flex 1
      .title
        font-size .875rem
        color #262626
      .info
        display flex
        justify-content space-between
        padding-right .625rem
        .price
          color red
          font-weight 600
          i
            font-weight 400
            font-size .75rem
            font-style: normal
        .num
          display flex
          align-items center
          input
            width 2.5rem
            font-size .875rem
            border 0
            outline none
            text-align center
          button
            width 1.25rem
            height 1.25rem
            border 1px solid black
            background-color black
            color white
      .remove
        font-size .875rem
        display flex
        flex-direction row-reverse
        align-items center
        span
          padding 0 .625rem
          color #262626
.CartView
    flex 1
    display flex
    flex-direction column
    .header
        height 2.875rem
    .cartMain
        flex 1
        padding 0 .625rem
        box-sizing border-box
        background-color rgb(242,242,242)
        .van-submit-bar
          border-top 1px solid #ccc
          background hsla(0,0%,100%,.95)
          bottom 50px
.van-empty
    padding 50px 0
.custom-image .van-empty__image
    width 90px
    height 90px
.van-divider::after, .van-divider::before
    border-color #555
.cartlist
  min-height 12.5rem
</style>
<script>
import Vue from 'vue'
import proList from '@/components/proList.vue'
// 导入api请求接口方法
import { getProlist, getList, getUpdateNum, getRemove, getSelectOne, getSelectAll, getAaddOrder } from '@/api/Cart'
// 导入vant组件
import { NavBar, Icon, Popover, Empty, Divider, ShareSheet, Toast, Dialog, SubmitBar, Checkbox } from 'vant'
Vue.use(NavBar)
Vue.use(Icon)
Vue.use(Popover)
Vue.use(Empty)
Vue.use(ShareSheet)
Vue.use(Divider)
Vue.use(Toast)
Vue.use(Dialog)
Vue.use(SubmitBar)
Vue.use(Checkbox)
export default {
  data () {
    return {
      // 右上角气泡弹出层数据
      actions: [{ text: '首页', icon: 'home-o', index: 0 }, { text: '分类搜素', icon: 'apps-o', index: 1 }, { text: '我的嗨购', icon: 'user-o', index: 2 }, { text: '浏览记录', icon: 'clock-o', index: 3 }, { text: '我的关注', icon: 'like-o', index: 4 }, { text: '分享', icon: 'guide-o', index: 5 }],
      // 气泡弹出层状态
      showPopover: false,
      // 分享模块弹出层状态
      showShare: false,
      // 是否处于上拉加载更多状态
      loading: false,
      // 推荐数据是否加载完毕
      finished: false,
      // 当前用户id
      userid: '',
      // 购物车数据
      cartList: [],
      // 全选状态
      checked: false,
      // 总价
      totalPrice: 0,
      // 第一次上拉默认页码
      number: 2,
      // 分享模块的数据
      options: [
        [
          { name: '微信', icon: 'wechat' },
          { name: '朋友圈', icon: 'wechat-moments' },
          { name: '微博', icon: 'weibo' },
          { name: 'QQ', icon: 'qq' }
        ],
        [
          { name: '复制链接', icon: 'link' },
          { name: '分享海报', icon: 'poster' },
          { name: '二维码', icon: 'qrcode' },
          { name: '小程序码', icon: 'weapp-qrcode' }
        ]
      ],
      // 推荐列表数据
      prolist: [],
      // 用户登录状态
      userState: '',
      // 订单状态
      orderState: []
    }
  },
  methods: {
    // 分享模块跳转和方法判断
    onSelect (action) {
      console.log(action.index)
      switch (action.index) {
        case 0:
          this.$router.push('/home')
          break
        case 1:
          this.$router.push('/kind')
          break
        case 2:
          this.$router.push('/user')
          break
        case 3:
          console.log('我是浏览记录模块')
          break
        case 4:
          console.log('我是关注模块')
          break
        case 5:
          console.log('我是分享模块')
          this.showShare = true
          break
      }
    },
    // 上拉加载更多推荐数据
    onLoad () {
      this.loading = true
      getProlist({ count: this.number }).then((res) => {
        this.loading = false
        if (res.data.length) {
          this.prolist = [...this.prolist, ...res.data]
          this.number++
        } else {
          this.finished = true
        }
      })
    },
    // 减数量
    subtract (cartid, num) {
      if (num > 1) {
        getUpdateNum({ cartid: cartid, num: num - 1 }).then((res) => {
          const index = this.cartList.findIndex(item => item.cartid === cartid)
          this.cartList[index].num--
          this.totalprice()
        })
      } else {
        Toast('商品数量最少为1')
      }
      console.log(cartid, num)
    },
    // 加数量
    addition (cartid, num) {
      if (num < 999) {
        getUpdateNum({ cartid: cartid, num: num + 1 }).then((res) => {
          const index = this.cartList.findIndex(item => item.cartid === cartid)
          this.cartList[index].num++
          this.totalprice()
        })
      } else {
        Toast('商品数量最多为999')
      }
    },
    // 删除当前点击的商品
    removeId (cartid) {
      Dialog.confirm({
        title: '警告',
        message: '确定要删除此商品？'
      })
        .then(() => {
          // on confirm
          const index = this.cartList.findIndex(item => item.cartid === cartid)
          this.cartList.splice(index, 1)
          getRemove({ cartid: cartid }).then((res) => {
            this.totalprice()
          })
        })
        .catch(() => {
          // on cancel
          console.log('取消删除')
        })
    },
    // 提交订单事件
    onSubmit () {
      const flag = this.cartList.some(item => item.flag)
      if (flag) {
        getAaddOrder({ userid: this.userid }).then((res) => {
          if (res.code === '200') {
            this.orderState.unshift({ key: res.time, isflag: false, userid: this.userid })
            // 更新全局状态中的订单状态
            this.$store.commit('changeOrder', this.orderState)
            // 将订单状态存储到本地存储
            localStorage.setItem('orderState', JSON.stringify(this.orderState))
            this.$router.push({ name: 'order', params: { timeId: res.time } })
          }
        })
      } else {
        Toast('请选择商品')
      }
    },
    // 全选事件
    checkAll () {
      this.cartList.map((item) => {
        item.flag = this.checked
        return item
      })
      this.totalprice()
      // 全选接口
      getSelectAll({ userid: this.userid, type: this.checked })
    },
    // 数组遍历求总价
    totalprice () {
      this.totalPrice = 0
      this.cartList.forEach(element => {
        if (element.flag) {
          this.totalPrice = this.totalPrice + element.num * element.originprice
        }
      })
      this.totalPrice *= 100
    },
    // 多选框点击事件
    checkbox (val) {
      this.checked = this.cartList.every(item => item.flag)
      this.totalprice()
      // 改变单个商品的选择状态
      getSelectOne({ cartid: val.cartid, flag: val.flag })
    },
    // 移入关注事件
    move () {
      console.log('移入关注')
    }
  },
  mounted () {
    // 获取订单状态
    this.orderState = this.$store.state.orderState ? this.$store.state.orderState : []
    // 重定向根据用户登录状态进行重定向
    this.userState = this.$store.state.userState ? this.$store.state.userState : this.$router.push('/login')
    // 获取用户id属性
    this.userid = this.$store.state.userId
    // 获取推荐列表数据
    getProlist().then((res) => {
      this.prolist = res.data
    })
    // 获取当前用户购物车数据
    getList({ userid: this.userid }).then((res) => {
      if (res.code === '200') {
        this.cartList = res.data
        // 默认选中的初始总价
        this.totalprice()
        // 设置默认全选状态
        this.checked = res.data.every(item => item.flag)
      } else {
        this.cartList = false
      }
    })
  },
  filters: {
    // 获取总价整数部分
    setPriceInt (val) {
      if (val) {
        return parseInt(val)
      }
    },
    // 获取总价小数部分
    setPriceFloat (val) {
      if (val) {
        return val * 100 % 100 >= 10 ? val * 100 % 100 : '0' + val * 100 % 100
      }
    }
  },
  // 注册自定义组件
  components: {
    proList
  }
}
</script>
